<template>
  <div>
    <div class="project-manage-type-list" v-loading="loading">
      <el-row class="project-manage-type-list-header" type="flex" justify="space-between">
        <div>
          <h2>{{ $t('common.projectManage.projectTypeName') }}</h2>
          <p>{{ $t('projectManage.projectType.tip1') }}</p>
        </div>
        <div>
          <el-button type="primary" @click="handleClickNew"><i class="iconfont icon-add2"></i>{{ $t('common.base.create') }}</el-button>
        </div>
      </el-row>
      <div class="project-manage-type-list-con">
        <draggable v-bind="{ animation: 380, ghostClass: 'ghost' }" v-model="templateList" tag="div" @change="updateTemplateSort" class="project-manage-type-list-con-group">
          <project-card-list class="project-manage-type-list-con-group-item" v-for="item in templateList" :key="item.id" :templateList="item" @handleDelete="handleDelete" @changeSwitch="changeSwitch" @clickEdit="handleClickEdit" :isShowSwitch="true"></project-card-list>
        </draggable>
      </div>
    </div>

    <!-- 新建 -->
    <NewProjectTypeDialog ref="newRef" @submitSave="submitSave" />
    <AddTaskTypeDialog ref="addTaskTypeDialogDom" mode="projectType" :visiable.sync="addTypeDialogShow" :task-type-list="taskTypeList" @submit="createType"></AddTaskTypeDialog>
  </div>
</template>
<script>
import { reactive, toRefs, onMounted, ref, computed } from 'vue';
import draggable from 'vuedraggable';
import ProjectCardList from '@src/modules/setting/projectManage/components/CardList.vue';
import NewProjectTypeDialog from '@src/modules/setting/projectManage/components/NewProjectTypeDialog.vue';

import { projectTypeList, projectTypeDelete, projectTypeCreate, projectTypeUpdateOrder, projectTypeUpdateStatus } from '@src/api/ProjectManage.ts';
import { toast } from '@src/util/platform';
import { notification } from '@src/util/platform';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import AddTaskTypeDialog from '@src/modules/setting/task/taskTypeSetting/manage/components/AddTaskTypeDialog.vue';

import { MessageBox } from 'element-ui';

import i18n from '@src/locales';

export default {
  name: 'project-type-list',
  components: {
    draggable,
    ProjectCardList,
    NewProjectTypeDialog,
    AddTaskTypeDialog,
  },
  setup() {
    const newRef = ref();
    const addTypeDialogShow = ref(false);
    const addTaskTypeDialogDom = ref(null);

    const state = reactive({
      loading: false,
      templateList: [],
    });

    // 获取目前开启的模板数据
    const enableTypeNum = computed(() => {
      return state.templateList.filter(item => item.enabled).length;
    });

    // 获取模板列表
    const fetchTemplateList = async () => {
      state.loading = true;
      try {
        let ret = await projectTypeList();

        const { success, message, data } = ret || {};

        if (!success) return toast(message, 'error');

        state.templateList = (data || []).map(item => {
          return {
            templateName: item.name,
            ...item,
          };
        });
      } catch (err) {
        console.log('error => fetchTemplateList', err);
      } finally {
        state.loading = false;
      }
    };

    const taskTypeList = computed(() => {
      let arr = [];
      state.templateList.forEach(i => {
        arr.push({
          id: i.id,
          name: i.name,
        });
      });
      return arr;
    });

    // 新建
    const handleClickNew = () => {
      addTypeDialogShow.value = true;
      // newRef.value.dialogVisible = true;
      // newRef.value.resetField();
    };

    // 拖拽排序
    const updateTemplateSort = () => {
      let orderParams = [];
      orderParams = state.templateList.map((item, idx) => {
        return {
          id: item.id,
          orderId: idx,
        };
      });

      if (orderParams.length <= 0) return;

      projectTypeUpdateOrder(orderParams).then(res => {
        let { success, message } = res || {};

        if (!success) return toast(message, 'error');

        toast(i18n.t('common.base.tip.updateSuccess'), 'success');
      });
    };

    // 删除
    const handleDelete = ({ id, name }) => {
      MessageBox.confirm(i18n.t('projectManage.projectType.deleteTip', { templateName: name }), i18n.t('projectManage.projectType.deleteTitle'), {
        confirmButtonText: i18n.t('common.base.makeSure'),
        cancelButtonText: i18n.t('common.base.cancel'),
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            projectTypeDelete([id]).then(res => {
              instance.confirmButtonLoading = false;

              if (!res.success) {
                return toast(res.message, 'error');
              }

              toast(i18n.t('common.base.tip.deleteSuccess'), 'success');

              done();

              fetchTemplateList();
            });
          } else {
            instance.confirmButtonLoading = false;
            done();
          }
        },
      });
    };

    // change开关
    const changeSwitch = async (enabled, row) => {
      if (!Boolean(enabled) && enableTypeNum.value <= 1) {
        notification({
          title: i18n.t('projectManage.projectType.tip2'),
          type: 'error',
        });
        return;
      }

      try {
        let ret = await projectTypeUpdateStatus({
          id: row.id,
          status: enabled,
        });

        const { success, message } = ret || {};

        if (!success) return toast(message, 'error');

        toast(i18n.t('common.base.tip.modifySuccess'), 'success');

        fetchTemplateList();
      } catch (err) {
        console.log('error => changeSwitch', err);
      }
    };

    // 跳转项目类型表单设计器页面
    const jumpProjectTypeDesign = ({ id }) => {
      let fromId = window.frameElement?.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageProjectManageType,
        params: `templateId=${id}`,
        fromId,
      });
    };

    // 新建保存
    const submitSave = ({ templateName, color, templateId }) => {
      if (!newRef.value) return; // 以防万一，一般是存在的。

      projectTypeCreate({
        name: templateName,
        color,
        templateId,
      })
        .then(res => {
          if (!res.success) return toast(res.message, 'error');

          const row = {
            id: res.data,
          };

          newRef.value.dialogVisible = false;
          addTaskTypeDialogDom.value.cancel();
          addTaskTypeDialogDom.value.clickTaskType = '';

          fetchTemplateList();

          jumpProjectTypeDesign(row);
        })
        .finally(() => {
          newRef.value.saveLoading = false;
        });
    };

    // 编辑
    const handleClickEdit = row => {
      jumpProjectTypeDesign(row);
    };

    function createType(info) {
      const { typeName, templetId, color } = info;
      submitSave({ templateName: typeName, color, templateId:templetId });
    }

    onMounted(() => {
      fetchTemplateList();
    });

    return {
      newRef,
      enableTypeNum,
      ...toRefs(state),
      handleClickNew,
      updateTemplateSort,
      handleDelete,
      changeSwitch,
      submitSave,
      handleClickEdit,
      addTypeDialogShow,
      createType,
      taskTypeList,
      addTaskTypeDialogDom,
    };
  },
};
</script>
<style lang="scss" scoped>
@import './projectTypeList.scss';
</style>
